package com.burningtower.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.burningtower.common.PageResult;
import com.burningtower.common.Result;
import com.burningtower.entity.Role;
import com.burningtower.service.IRoleResourceService;
import com.burningtower.service.IRoleService;
import com.burningtower.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 角色 前端控制器
 * </p>
 *
 * @author zhe
 * @since 2017-11-17
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService service;
    @Autowired
    private IRoleResourceService roleResourceService;

    @RequestMapping("dataGrid")
    public PageResult<Role> dataGrid(String order, Integer page, Integer rows, String sort){
        Page<Role> p=new Page<>(page,rows,sort);
        p.setAsc("asc".equals(order));
        Page<Role> rolePage = service.selectPage(p);
        PageResult<Role> pageResult=new PageResult<>();
        pageResult.setTotal(rolePage.getTotal());
        pageResult.setRows(rolePage.getRecords());
        return pageResult;
    }
    @RequestMapping("findResourceIdListByRoleId")
    public Result<String> findResourceIdListByRoleId(Long id){
        List<Long> list = roleResourceService.selectResourceIdListByRoleId(id);
        String ids=new String("");
        for(int i=0;i<list.size();i++){
            ids+=list.get(i).toString()+(i==(list.size()-1)?"":",");
        }
        Result result=new Result();
        result.setObj(ids);
        return result;
    }
    @RequestMapping("tree")
    public List<TreeVo> tree(){
        List<Role> roles = service.selectList(null);
        List<TreeVo> vos=new ArrayList<>();
        for(Role role:roles){
            TreeVo vo = service.toVo(role);
            vos.add(vo);
        }
        return vos;
    }
    @RequestMapping("grant")
    public Result grant(Long id,String resourceIds){
        service.grant(id,resourceIds);
        return new Result("授权成功");
    }
    @RequestMapping("delete")
    public Result delete(Long id){
        service.deleteById(id);
        return new Result("删除成功！");
    }
    @RequestMapping("edit")
    public Result edit(Role role){
        service.updateById(role);
        return new Result("编辑成功！");
    }
    @RequestMapping("add")
    public Result add(Role role){
        service.insert(role);
        return new Result("添加成功");
    }
}

